<template>
  <div>
    <!-- 功能条 -->
    <el-row class="buttonRow">
      <el-col :span="2">
        <el-button type="primary" size="mini" @click="openCreateFormDialog">创建权限</el-button>
      </el-col>
      <el-col :span="22">
        <el-input
          v-model="getReq.keyword"
          size="mini"
          placeholder="请输入关键词..."
          clearable
          @keyup.enter.native="search"
          @clear="clearKeyword"
        >
          <el-button slot="append" icon="el-icon-search" @click="search" />
        </el-input>
      </el-col>
    </el-row>
    <!-- 列表 -->
    <el-row class="tableRow">
      <div class="tableDiv">
        <el-table :data="tableAry" border stripe @expand-change="expandTable">
          <el-table-column label="序号" prop="index" width="50px" :show-overflow-tooltip="true" />
          <el-table-column label="详情" width="50px" type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="table-expand">
                <el-form-item label="具备该权限的用户">
                  <span>{{ props.row.hasUsers }}</span>
                </el-form-item>
                <el-form-item label="具备该权限的用户群">
                  <span>{{ props.row.hasGroups }}</span>
                </el-form-item>
                <el-form-item label="Id">
                  <span>{{ props.row.id }}</span>
                </el-form-item>
                <el-form-item label="创建时间">
                  <span>{{ props.row.gmtCreate }}</span>
                </el-form-item>
                <el-form-item label="更新时间">
                  <span>{{ props.row.gmtModified }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="权限键名" prop="roleKey" width="180px" :show-overflow-tooltip="true" />
          <el-table-column
            label="权限名称"
            prop="roleName"
            width="180px"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="说明" prop="remark" :show-overflow-tooltip="true" />
          <el-table-column label="操作" width="360px">
            <template slot-scope="scope">
              <template>
                <el-button type="primary" size="mini" @click="setUsers(scope.row)">分配用户</el-button>
              </template>
              <template>
                <el-button type="primary" size="mini" @click="setGroups(scope.row)">分配用户群</el-button>
              </template>
              <template>
                <el-button type="warning" size="mini" @click="openEditFormDiglog(scope.row)">编辑</el-button>
              </template>
              <template>
                <el-button type="danger" size="mini" @click="delRole(scope.row)">删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>
    <!-- 页条 -->
    <el-row type="flex" justify="center" class="pageRow">
      <el-pagination
        :current-page="getReq.currentPage"
        :page-sizes="[10, 25, 50]"
        :page-size="getReq.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-row>

    <!-- 表单对话框 -->
    <el-dialog
      :visible.sync="formDialogVisible"
      width="50%"
      top="5vh"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-row class="formTitleRow">
        <div class="formTitle">{{ formTitle }}</div>
      </el-row>
      <el-divider />
      <el-row class="formRow">
        <el-form ref="form" :rules="rules" :model="form" label-width="120px">
          <el-form-item label="权限键名" prop="roleKey">
            <el-input ref="input" v-model="form.roleKey" />
          </el-form-item>
          <el-form-item label="权限名称" prop="roleName">
            <el-input v-model="form.roleName" />
          </el-form-item>
          <el-form-item label="说明" prop="remark">
            <el-input v-model="form.remark" type="textarea" :autosize="{ minRows:4, maxRows: 8}" />
          </el-form-item>
        </el-form>
      </el-row>
      <el-divider />
      <el-row>
        <div class="formButtonDiv">
          <el-button size="mini" class="formButton" @click="closeFormDialog">取 消</el-button>
          <el-button type="primary" size="mini" class="formButton" @click="submit">提 交</el-button>
        </div>
      </el-row>
    </el-dialog>
    <!-- 配置对话框 -->
    <el-dialog
      :visible.sync="configDialogVisible"
      width="50%"
      top="5vh"
      :close-on-click-modal="false"
      @close="closeConfigDialog"
    >
      <ConfigPage
        v-if="configDialogVisible"
        :in-config-target="configTarget"
        :in-config-ary="configAry"
        @submitConfig="submitConfig"
        @closeConfigPage="closeConfigDialog"
      />
      <!-- v-if="configDialogVisible" 做到创建销毁组件，可以在组件中使用生命周期钩子 -->
    </el-dialog>
  </div>
</template>

<script>
import ConfigPage from '@/components/fsd/ConfigPage'
import { createRoleAPI, getRolesAPI, editRoleAPI } from '@/util/back_front_api/roles.js'
import { getUsersAllAPI } from '@/util/back_front_api/users.js'
import { getUsersByRoleAPI, changeUsersByRoleAPI } from '@/util/back_front_api/users_roles.js'
import { getGroupsAllAPI } from '@/util/back_front_api/groups.js'
import { getGroupsByRoleAPI, changeGroupsByRoleAPI } from '@/util/back_front_api/groups_roles.js'

export default {
  name: 'fsdrole',
  components: {
    ConfigPage,
  },
  data() {
    return {
      // 列表
      tableAry: [],
      // 页条
      total: 0,
      // 表单对话框
      formTitle: '',
      formDialogVisible: false,
      form: {
        roleKey: '',
        roleName: '',
        remark: '',
      },
      rules: {
        roleKey: [{ required: true, message: '请输入权限键名', trigger: 'blur' }],
        roleName: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
      },
      // 配置对话框
      configDialogVisible: false,
      configTarget: {
        id: '',
        dialogTitle: '',
        itemTitle: '',
        name: '',
        type: '',
      },
      configAry: [],
      // 请求
      getReq: {
        keyword: '',
        currentPage: 1,
        pageSize: 10,
      },
      createReq: {
        roleKey: '',
        roleName: '',
        remark: '',
      },
      editReq: {
        id: '',
        roleKey: '',
        roleName: '',
        remark: '',
      },
      getByRoleReq: {
        id: '',
      },
      changeReq: {
        id: '',
        idAry: [],
      },
    }
  },
  created() {
    // 使用keepalive后不能刷新的情况，在activated中获取list
    this.getRoles()
  },
  methods: {
    // 功能条
    clearKeyword() {
      this.getReq.keyword = ''
      this.getRoles()
    },
    search() {
      this.getReq.currentPage = 1
      this.getRoles()
    },
    // 列表
    async expandTable(row) {
      let usersByRole
      let groupsByRole
      this.getByRoleReq.id = row.id
      row.hasUsers = ''
      row.hasGroups = ''
      try {
        usersByRole = (await getUsersByRoleAPI(this.getByRoleReq)).data
        groupsByRole = (await getGroupsByRoleAPI(this.getByRoleReq)).data
      } catch (err) {
        console.log(err)
      }

      usersByRole.forEach((item) => {
        if (row.hasUsers === '') {
          row.hasUsers = item.users.userName + '(' + item.users.jobNumber + ')'
        } else {
          row.hasUsers = row.hasUsers + '、' + item.users.userName + '(' + item.users.jobNumber + ')'
        }
      })
      groupsByRole.forEach((item) => {
        if (row.hasGroups === '') {
          row.hasGroups = item.groups.groupName
        } else {
          row.hasGroups = row.hasGroups + '、' + item.groups.groupName
        }
      })
      if (row.hasUsers === '') {
        row.hasUsers = '（无）'
      }
      if (row.hasGroups === '') {
        row.hasGroups = '（无）'
      }
    },
    delRole() {},
    // 页条
    handleSizeChange(size) {
      this.getReq.pageSize = size
      this.getRoles()
    },
    handleCurrentChange(page) {
      this.getReq.currentPage = page
      this.getRoles()
    },
    // 表单对话框
    openCreateFormDialog() {
      this.formDialogVisible = true

      this.$nextTick(() => {
        this.$refs.input.focus()
        this.$refs.form.resetFields()

        this.formTitle = '创建权限'
      })
    },
    openEditFormDiglog(row) {
      this.editReq.id = ''
      this.editReq.roleKey = ''
      this.editReq.roleName = ''
      this.editReq.remark = ''

      this.formDialogVisible = true

      this.$nextTick(() => {
        this.$refs.input.focus()
        this.$refs.form.resetFields()

        this.formTitle = '编辑权限'
        this.form.roleKey = row.roleKey
        this.form.roleName = row.roleName
        this.form.remark = row.remark

        this.editReq.id = row.id
      })
    },
    closeFormDialog() {
      this.formTitle = ''
      this.formDialogVisible = false
    },
    submit() {
      if (this.formTitle === '创建权限') {
        this.create()
      } else if (this.formTitle === '编辑权限') {
        this.edit()
      } else {
        this.utilMessage.warning('formTitle有误。')
      }
    },
    create() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm('将会创建你所设置的权限, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              this.createReq.roleKey = this.form.roleKey
              this.createReq.roleName = this.form.roleName
              this.createReq.remark = this.form.remark
              createRoleAPI(this.createReq)
                .then((res) => {
                  this.utilMessage.success(res.msg)
                  console.log(res)
                  setTimeout(() => {
                    this.getRoles()
                  }, 500)
                })
                .catch((err) => {
                  console.log(err)
                })
              this.closeFormDialog()
            })
            .catch(() => {
              return false
            })
        } else {
          console.log('error submit!!')
          this.utilMessage.warning('请正确输入信息。')
          return false
        }
      })
    },
    edit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm('将会修改你所选的权限的信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              this.editReq.roleKey = this.form.roleKey
              this.editReq.roleName = this.form.roleName
              this.editReq.remark = this.form.remark
              editRoleAPI(this.editReq)
                .then((res) => {
                  this.utilMessage.success(res.msg)
                  console.log(res)
                  setTimeout(() => {
                    this.getRoles()
                  }, 500)
                })
                .catch((err) => {
                  console.log(err)
                })
              this.closeFormDialog()
            })
            .catch(() => {
              return false
            })
        } else {
          this.utilMessage.warning('请正确输入信息。')
          return false
        }
      })
    },
    // 配置对话框
    async setUsers(row) {
      this.configAry = [] // configTarget赋值
      this.configTarget.dialogTitle = '分配该权限所拥有的用户'
      this.configTarget.itemTitle = '请选择用户：'
      this.configTarget.name = row.roleName
      this.configTarget.id = row.id
      this.configTarget.type = 'checkbox'

      let usersAll = [] // configAry赋值
      let usersByRole = []
      this.getByRoleReq.id = row.id
      try {
        usersAll = (await getUsersAllAPI()).data
        usersByRole = (await getUsersByRoleAPI(this.getByRoleReq)).data
      } catch (err) {
        console.log(err)
      }
      let obj = {}
      let i
      obj.id = '0'
      obj.checkItem = []
      obj.title = ''
      usersAll.forEach((userInUsersAll) => {
        let objItem = {}
        objItem.id = userInUsersAll.id
        objItem.display = userInUsersAll.userName + '(' + userInUsersAll.jobNumber + ')'
        objItem.col = 6
        objItem.checked = false
        for (i = 0; i < usersByRole.length; i += 1) {
          if (userInUsersAll.id === usersByRole[i].userId) {
            objItem.checked = true
            usersByRole.splice(i, 1)
            break
          }
        }
        obj.checkItem.push(objItem)
      })
      this.configAry.push(obj)

      this.configDialogVisible = true
    },
    async setGroups(row) {
      this.configAry = [] // configTarget赋值
      this.configTarget.dialogTitle = '分配该权限所拥有的用户群'
      this.configTarget.itemTitle = '请选择用户群：'
      this.configTarget.name = row.roleName
      this.configTarget.id = row.id
      this.configTarget.type = 'checkbox'

      let groupsAll = [] // configAry赋值
      let groupsByRole = []
      this.getByRoleReq.id = row.id
      try {
        groupsAll = (await getGroupsAllAPI()).data
        groupsByRole = (await getGroupsByRoleAPI(this.getByRoleReq)).data
      } catch (err) {
        console.log(err)
      }
      let obj = {}
      let i
      obj.id = '0'
      obj.checkItem = []
      obj.title = ''
      groupsAll.forEach((groupInGroupsAll) => {
        let objItem = {}
        objItem.id = groupInGroupsAll.id
        objItem.display = groupInGroupsAll.groupName
        objItem.col = 6
        objItem.checked = false
        for (i = 0; i < groupsByRole.length; i += 1) {
          if (groupInGroupsAll.id === groupsByRole[i].groupId) {
            objItem.checked = true
            groupsByRole.splice(i, 1)
            break
          }
        }
        obj.checkItem.push(objItem)
      })
      this.configAry.push(obj)

      this.configDialogVisible = true
    },
    closeConfigDialog() {
      this.configDialogVisible = false
    },
    async submitConfig(outObj) {
      let msg
      this.closeConfigDialog()

      if (outObj.title === '分配该权限所拥有的用户') {
        this.changeReq.id = outObj.targetId
        this.changeReq.idAry = []

        outObj.configId.forEach((item) => {
          let tempObj = {}
          tempObj.roleId = outObj.targetId
          tempObj.userId = item
          this.changeReq.idAry.push(tempObj)
        })
        try {
          msg = (await changeUsersByRoleAPI(this.changeReq)).msg
          this.utilMessage.success(msg)
        } catch (err) {
          console.log(err)
        }
      } else if (outObj.title === '分配该权限所拥有的用户群') {
        this.changeReq.id = outObj.targetId
        this.changeReq.idAry = []

        outObj.configId.forEach((item) => {
          let tempObj = {}
          tempObj.roleId = outObj.targetId
          tempObj.groupId = item
          this.changeReq.idAry.push(tempObj)
        })
        try {
          msg = (await changeGroupsByRoleAPI(this.changeReq)).msg
          this.utilMessage.success(msg)
        } catch (err) {
          console.log(err)
        }
      } else {
        this.utilMessage.warning('提交配置种类出错')
      }
    },
    // 请求
    getRoles() {
      getRolesAPI(this.getReq)
        .then((result) => {
          let indexTemp
          this.total = result.data.count
          indexTemp = (this.getReq.currentPage - 1 >= 0 ? this.getReq.currentPage - 1 : 0) * this.getReq.pageSize
          this.tableAry = result.data.rows.map((item) => {
            this.$set(item, 'hasUsers', '')
            this.$set(item, 'hasGroups', '')
            this.$set(item, 'index', (indexTemp += 1))
            return item
          })
        })
        .catch((err) => {
          console.log(err)
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.buttonRow {
  margin: 10px;
}
.tableRow {
  margin: 10px;
}
.tableDiv {
  height: 530px;
  overflow-y: scroll;
}
.pageRow {
  margin: 5px;
}
.table-expand {
  font-size: 0;
}
.table-expand label {
  width: 90px;
  color: #99a9bf;
}
.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
}
.formTitle {
  text-align: center;
  letter-spacing: 10px;
  font-size: 20px;
}
.formRow {
  padding: 0px 100px 0px 100px;
}
.formButtonDiv {
  text-align: center;
}
.formButton {
  margin: 0px 30px 0px 30px;
}
.el-table th.gutter {
  display: table-cell !important;
}
// 滚动条
::-webkit-scrollbar {
  width: 3px;
}
::-webkit-scrollbar-thumb {
  background: #bcddff;
  border-radius: 5px;
}
</style>
